package com.example.healthapp.ui.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.example.healthapp.R;
import com.example.healthapp.permission.PermissionListener;
import com.example.healthapp.permission.PermissionRequest;
import com.example.healthapp.ui.fragment.FunctionFragment;
import com.example.healthapp.ui.fragment.MineFragment;
import com.example.healthapp.ui.fragment.BleFragment;
import com.example.healthapp.ui.fragment.UploadTestFragment;
import com.example.healthapp.utils.SPManage;
import kt_test.ui.fragment.OxygenDataViewerFragment;
import kt_test.ui.fragment.OxygenQueryFragment;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    FragmentManager fragmentManager;
    FragmentTransaction fragmentTransaction;
    Fragment[] fragment = new Fragment[] {
            new UploadTestFragment(),
            new FunctionFragment(),
            new OxygenQueryFragment(), // 这是血氧记录的新Fragment
            new BleFragment() // 这是蓝牙的Fragment
    };

    LinearLayout main_info_layout, main_find_layout, main_me_layout, main_ble_layout;
    TextView main_info_txt, main_find_txt, main_me_txt, main_ble_txt, main_title;

    // 用户信息 TextView
    TextView user_info;

    // 退出按钮
    Button logoutButton;

    private final String TAG = "MainActivity";

    private final String[] requestPermissionArray = new String[] {
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
    };

    private BroadcastReceiver batInfoReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
                int level = intent.getIntExtra("level", 0);
                int scale = intent.getIntExtra("scale", 100);
                int percent = level * 100 / scale;
                Toast.makeText(MainActivity.this, "电量：" + percent + "%", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        loadUserInfo(); // 加载用户信息
        reference();    // 修改这里以加载正确的Fragment
        event();
        initPermissions();

        // 设置退出按钮点击事件
        logoutButton = findViewById(R.id.logout_button);
        logoutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                logout();  // 调用退出登录的方法
            }
        });
    }

    private void initView() {
        main_info_layout = findViewById(R.id.main_info_layout);
        main_find_layout = findViewById(R.id.main_find_layout);
        main_me_layout = findViewById(R.id.main_me_layout);
        main_ble_layout = findViewById(R.id.main_ble_layout);
        main_info_txt = findViewById(R.id.main_info_txt);
        main_find_txt = findViewById(R.id.main_find_txt);
        main_me_txt = findViewById(R.id.main_me_txt);
        main_ble_txt = findViewById(R.id.main_ble_txt);
        main_title = findViewById(R.id.main_title);

        // 初始化 user_info
        user_info = findViewById(R.id.user_info);
    }

    // 新增方法：读取并显示用户信息
    private void loadUserInfo() {
        String userId = SPManage.getSP(this, "account").getString("userId");
        String gender = SPManage.getSP(this, "account").getString("gender");
        String age = SPManage.getSP(this, "account").getString("age");

        // 组装展示文本
        String info = "欢迎回来，用户ID: " + userId + "，性别: " + gender + "，年龄: " + age + "岁";

        // 设置到 TextView 上
        user_info.setText(info);
    }

    private void event() {
        registerReceiver(batInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }

    private void reference() {
        fragmentManager = getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();

        // 修改：默认加载 BleFragment
        fragmentTransaction.add(R.id.main_fragment, fragment[3]); // fragment[3] 对应 BleFragment
        setChangeTableIcon(3); // 设置选中的 Tab 为蓝牙

        fragmentTransaction.commit();
    }

    public void onclick(View view) {
        if (view.getId() == R.id.main_info_layout) {
            setFragmentManager(0);
        } else if (view.getId() == R.id.main_find_layout) {
            setFragmentManager(1);
        } else if (view.getId() == R.id.main_me_layout) {
            setFragmentManager(2);
        } else if (view.getId() == R.id.main_ble_layout) {
            setFragmentManager(3);
        }
    }

    private void setFragmentManager(int index) {
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.main_fragment, fragment[index]);
        fragmentTransaction.commit();
        setChangeTableIcon(index);
    }

    private void setChangeTableIcon(int index) {
        main_info_txt.setTextColor(Color.parseColor("#1C1C1C"));
        main_find_txt.setTextColor(Color.parseColor("#1C1C1C"));
        main_me_txt.setTextColor(Color.parseColor("#1C1C1C"));
        main_ble_txt.setTextColor(Color.parseColor("#1C1C1C"));
        main_info_txt.setBackground(null);
        main_find_txt.setBackground(null);
        main_me_txt.setBackground(null);
        main_ble_txt.setBackground(null);

        switch (index) {
            case 0:
                main_info_txt.setTextColor(Color.parseColor("#FFFFFF"));
                main_info_txt.setBackgroundResource(R.drawable.bule_circle);
                main_title.setText("血氧文件上传");
                break;
            case 1:
                main_find_txt.setTextColor(Color.parseColor("#FFFFFF"));
                main_find_txt.setBackgroundResource(R.drawable.bule_circle);
                main_title.setText("功能");
                break;
            case 2:
                main_me_txt.setTextColor(Color.parseColor("#FFFFFF"));
                main_me_txt.setBackgroundResource(R.drawable.bule_circle);
                main_title.setText("血氧记录");
                break;
            case 3:
                main_ble_txt.setTextColor(Color.parseColor("#FFFFFF"));
                main_ble_txt.setBackgroundResource(R.drawable.bule_circle);
                main_title.setText("蓝牙");
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(batInfoReceiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(batInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }

    private void initPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            PermissionRequest permissionRequest = new PermissionRequest();
            permissionRequest.requestRuntimePermission(this, requestPermissionArray, new PermissionListener() {
                @Override
                public void onGranted() {
                    Log.d(TAG, "所有权限已授予");
                }

                @Override
                public void onDenied(List<String> deniedPermissions) {
                    for (String deniedPermission : deniedPermissions) {
                        Log.e(TAG, "被拒绝权限：" + deniedPermission);
                    }
                }
            });
        }
    }

    // 退出登录的方法
    private void logout() {
        // 跳回登录页面
        Toast.makeText(MainActivity.this, "退出登录成功", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();  // 结束当前的 MainActivity
    }
}
